import os
import json

def getCitationCount(a_node):
    try:
        return a_node['citation_count']
    except:
        return 0

def storeTitles(dic, id_clusters):
    print("storeTitles started")
    theID = id_clusters.split('_')[0]
    clusters = id_clusters.split('_')[1]
    os.system('mkdir json/titleLists/' + theID)
    os.system('mkdir json/titleLists/' + theID + '/' + clusters)
    for cluster_id in list(dic['cluster']):
        nodes = dic['cluster'][cluster_id]['nodes']
        nodes = sorted(nodes, key = getCitationCount, reverse = True)
        nodeTitles = []
        for node in nodes:
            nodeTitles.append( [node['id'], node['title']] )
        i = 0
        f = open('json/titleLists/' + theID + '/' + clusters + '/' + cluster_id + '.json', 'w')
        str2write = json.dumps( {'nodeTitles': nodeTitles} )
        f.write(str2write)
        f.close()
    print("storeTitles finished")
